package com.komlin.msgpush.mipushmsg;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

import androidx.core.os.BuildCompat;
import android.util.Log;

import com.komlin.msgpush.KomlinPushManager;
import com.xiaomi.mipush.sdk.ErrorCode;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.xiaomi.mipush.sdk.MiPushCommandMessage;
import com.xiaomi.mipush.sdk.MiPushMessage;
import com.xiaomi.mipush.sdk.PushMessageReceiver;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @Author lifq
 * 创建时间： 2019/5/24 16:11
 * 包名： com.komlin.msgpush
 * 功能描述：
 **/
public class MipushBroadcast extends PushMessageReceiver {
    //透传消息到达客户端时调用
    //作用：可通过参数message从而获得透传消息，具体请看官方SDK文档
    @Override
    public void onReceivePassThroughMessage(Context context, MiPushMessage message) {
        //打印消息方便测试
        System.out.println("透传消息到达了");
        System.out.println("透传消息是" + message.toString());
    }


    //通知消息到达客户端时调用
    //注：应用在前台时不弹出通知的通知消息到达客户端时也会回调函数
    //作用：通过参数message从而获得通知消息，具体请看官方SDK文档
    @Override
    public void onNotificationMessageArrived(Context context, MiPushMessage message) {
        //打印消息方便测试
        System.out.println("通知消息到达了");
        System.out.println("通知消息是" + message.toString());
        int bager = KomlinPushManager.getBager();
        ++bager;
        KomlinPushManager.setBager(bager);
        Intent intent = new Intent("xiaomi.MY_BROADCAST");
        if (Build.VERSION.SDK_INT >= 26) {
            intent.setComponent(new ComponentName("com.haierCamera.customapplication", "com.haierCamera.customapplication.ui.service.MyMiBroadcastReceiver"));
            intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
        }
        intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        intent.putExtra("bager", bager);
        context.sendBroadcast(intent);
        Log.i("TAG11", "bager:" + bager + "----------2");
        if (KomlinPushManager.getInstance().revicer != null) {
            KomlinPushManager.getInstance().revicer.onBadge(bager);
        }
    }

    //用户手动点击通知栏消息时调用
    //注：应用在前台时不弹出通知的通知消息到达客户端时也会回调函数
    //作用：1. 通过参数message从而获得通知消息，具体请看官方SDK文档
    //2. 设置用户点击消息后打开应用 or 网页 or 其他页面
    @Override
    public void onNotificationMessageClicked(final Context context, MiPushMessage message) {
        //打印消息方便测试
        System.out.println("通知消息是" + message.getDescription());
        System.out.println("点击后,会进入应用" + message.getTitle());
//        val intent = Intent(context, Test::class.java)
//        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP////创建新的activity并清除栈顶activity
//        context!!.startActivity(intent);
       /* Map<String, String> extra = message.getExtra();
        String type = extra.get("type");
        String data = extra.get("data");
        try {
            JSONObject jsonObject = new JSONObject(data);
            final Intent intent = new Intent();
            //0校园公告1班级公告2校园通知3班级通知4问卷调查
            if ("0".equals(type)) {
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.main.publics.SchoolNoticePublicActivity"));
                intent.putExtra("flag", 2).putExtra("title", "校园公告").putExtra("type", 1);
            } else if ("1".equals(type)) {
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.main.publics.SchoolNoticePublicActivity"));
                intent.putExtra("flag", 2).putExtra("title", "班级公告").putExtra("type", 2);
            } else if ("2".equals(type)) {
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.main.publics.SchoolNoticePublicActivity"));
                intent.putExtra("flag", 1).putExtra("title", "校园通知").putExtra("type", 2);
            } else if ("3".equals(type)) {
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.main.publics.SchoolNoticePublicActivity"));
                intent.putExtra("flag", 1).putExtra("title", "班级通知").putExtra("type", 3);
            } else if ("4".equals(type)) {
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.main.publics.SchoolNoticePublicActivity"));
                intent.putExtra("flag", 4).putExtra("title", "问卷调查").putExtra("type", 2);
            } else if ("5".equals(type)) {
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.new_leave.ApplyForLeaveListActivity"));
                intent.putExtra("title", "我的请假");
            } else if ("6".equals(type)) {
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.main.leave.LeaveStudentActivity"));
                intent.putExtra("title", "批学生假");
            } else if ("7".equals(type)) {
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.main.leave.LeaveTeachersActivity"));
                intent.putExtra("title", "批假初审").putExtra("type", 1);
            } else if ("8".equals(type)) {
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.main.leave.LeaveTeachersActivity"));
                intent.putExtra("title", "批假终审").putExtra("type", 2);
            } else if ("9".equals(type)) {
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.is_on_duty.DutyCalendarActivity"));
            } else if ("10".equals(type)) {
                //intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.is_on_duty.DutyCalendarActivity"));
            } else if ("11".equals(type)) {
                String classID = jsonObject.getString("classID");
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.main.bed.BedroomMsgActivity"));
                intent.putExtra("classId", classID);
            } else if ("12".equals(type)) {
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.visitors.VisitorsListActivity"));
            } else if ("13".equals(type)) {
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.leave_message.LeaveMessageTeacherActivity"));
            } else if ("14".equals(type)) {
                //学生留言
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.leave_message.LeaveMessageStudentActivity"));
            } else if ("15".equals(type)) {
                //教师带队 com.komlin.commonedition.ui.lead_the_tean
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.lead_the_tean.TeachersLeadTheTeamActivity"));
            } else if ("16".equals(type)) {
                //待处理保修
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.main.matters.MattersListActivity"));
            } else if ("17".equals(type)) {
                //安全巡查 com.komlin.commonedition.ui.safety_patrol
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.safety_patrol.SafetyPatrolActivity"));
            } else if ("18".equals(type)) {
                //代换课申请 com.komlin.commonedition.ui.safety_patrol
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.lesson_change.LessonChangeListActivity"));
            } else if ("19".equals(type)) {
                //开发者邀请 com.komlin.commonedition.ui.safety_patrol
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.lesson_change.LessonChangeInviteActivity"));
            } else {
                intent.setComponent(new ComponentName("com.komlin.iwatchteacher.commonedition", "com.komlin.commonedition.ui.main.MainActivity"));
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.setAction("android.intent.action.VIEW");
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    context.startActivity(intent);
                }
            }, 1000);
        } catch (JSONException e) {
            e.printStackTrace();
        }*/
    }

    //用来接收客户端向服务器发送命令后的响应结果。
    @Override
    public void onCommandResult(Context context, MiPushCommandMessage message) {
        String command = message.getCommand();
        List<String> arguments = message.getCommandArguments();
        System.out.println(command);
//        List<String> arguments = message.getCommandArguments();
//        String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null);
//        String cmdArg2 = ((arguments != null && arguments.size() > 1) ? arguments.get(1) : null);
        if (MiPushClient.COMMAND_REGISTER.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
//                mRegId = cmdArg1;
                //打印信息便于测试注册成功与否
                String mRegID = arguments.get(0);
                System.out.println("注册成功");
                Log.i("xiaomi", "mRegID:" + mRegID + "----------1");
            } else {
                System.out.println("注册失败");
            }
        }
    }

    //用于接收客户端向服务器发送注册命令后的响应结果。
    @Override
    public void onReceiveRegisterResult(Context context, MiPushCommandMessage message) {
        String command = message.getCommand();
        System.out.println(command);
        List<String> arguments = message.getCommandArguments();
//        String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null);
//        String cmdArg2 = ((arguments != null && arguments.size() > 1) ? arguments.get(1) : null);
        if (MiPushClient.COMMAND_REGISTER.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                //打印日志：注册成功
                System.out.println("注册成功");
//                mRegId = cmdArg1;
                String mAccount = arguments.get(0);
                Log.i("xiaomi", "mAccount:" + mAccount + "----------mAccount");
                if (KomlinPushManager.getInstance().revicer != null) {
                    KomlinPushManager.getInstance().revicer.onToken(mAccount);
                }
//                Log.e("MipushBroadcast", "userAccount is " + mAccount);
            } else {
                //打印日志：注册失败
                System.out.println("注册失败");
            }
        } else {
            System.out.println("其他情况" + message.getReason());
        }
    }

    @Override
    public void onRequirePermissions(Context context, String[] strings) {
        super.onRequirePermissions(context, strings);
    }

    //    private Message buildMessage() throws Exception {
//        String PACKAGENAME = "com.xiaomi.mipushdemo";
//        String messagePayload = “This is a message”;
//        String title = "Title"
//        String description = “notification description”;
//        Message message = new Message.Builder()
//                .title(title)
//                .description(description).payload(messagePayload)
//                .restrictedPackageName(MY_PACKAGE_NAME)
//                .passThrough(0)  //消息使用通知栏方式
//                .notifyType(1)
//                .extra(Constants.EXTRA_PARAM_NOTIFY_EFFECT, Constants.NOTIFY_LAUNCHER_ACTIVITY)
//                .build();
//        return message;
//    }

}
